package com.taotao.order.controller;

import com.taotao.cart.service.CartService;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.manager.pojo.TbItem;
import com.taotao.manager.pojo.TbUser;
import com.taotao.order.pojo.OrderInfo;
import com.taotao.order.service.OrderService;
import com.taotao.sso.service.UserLoginService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
public class OrderController {
    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private CartService cartService;
    @Autowired
    private OrderService orderService;


    @Value("${TT_CART_KEY}")
    private String TT_CART_KEY;
    @Value("${TT_TOKEN_KEY}")
    private String TT_TOKEN_KEY;


    @RequestMapping("/order/order-cart")
    public String showOrder(HttpServletRequest request, HttpServletResponse response) {
        //从cookie中获取用户的token
        //调用sso服务获取用户信息
        //必须是用户登录才展示
        //展示用户的送货地址--根据用户id查询该用户的配送地址--静态数据
        //展示支付方式  --从数据库获取支付方式--静态数据
        //调用购物车服务从redis中获取购物车商品列表
        //将列表传递到页面中
//        String token = CookieUtils.getCookieValue(request, TT_TOKEN_KEY);
//        if (StringUtils.isNotBlank(token)) {
//            TaotaoResult result = userLoginService.getUserByToken(token);
//            if(result.getStatus()==200){
//                //说明已登录
//                TbUser user = (TbUser) result.getData();
//                List<TbItem> cartList = cartService.getCartList(user.getId());
//                request.setAttribute("cartList",cartList);
//            }
//        }
        TbUser user = (TbUser) request.getAttribute("USER_INFO");
        List<TbItem> cartList = cartService.getCartList(user.getId());
        request.setAttribute("cartList", cartList);
        return "order-cart";
    }

    @RequestMapping(value = "/order/create", method = RequestMethod.POST)
    public String createOrder(HttpServletRequest request,OrderInfo info) {
        TbUser user = (TbUser) request.getAttribute("USER_INFO");
        info.setUserId(user.getId());
        info.setBuyerNick(user.getUsername());
        TaotaoResult result = orderService.createOrder(info);

        request.setAttribute("orderId",result.getData());
        request.setAttribute("payment",info.getPayment());
        DateTime dateTime = new DateTime();
        DateTime dateTime1 = dateTime.plusDays(3);
        request.setAttribute("date",dateTime1.toString("yyyy-MM-dd"));
        return "success";
    }

}
